package net.bat.web.grzx;


import java.util.List;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import net.bat.entity.Message;
import net.bat.entity.User;
import net.bat.filter.DateUtil;
import net.bat.service.account.AccountService;
import net.bat.service.account.ShiroDbRealm.ShiroUser;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class GrzxController {

	@Autowired
	private GrzxService gs;
	
	@Autowired
	private AccountService accountService;

	
	@RequestMapping(value = "/grzx", method = RequestMethod.GET)
	public String showDetail(Model model) {
		//通过ID在页面显示用户的资料
		long id = getCurrentUserId();
		model.addAttribute("user", gs.getUser(id));
		
		//根据ID查找对应的所有Message
		int uid=Integer.valueOf(getCurrentUserId().toString());
	    model.addAttribute("question", gs.getMessage(uid));
	    model.addAttribute("messize", gs.getMessage(uid).size());
	    
	    
 /*  for(int i=0;i<gs.getMessage(uid).size();i++){
	    	  Message question =gs.getMessage(uid).get(i);
                int pid=question.getPid();               
             if(pid==0){
            	 List<Message> questions=gs.getpMessage(pid);
            	 model.addAttribute("question", questions);    
            	 model.addAttribute("messize", questions.size());
            	}
	    }*/
	    
	    
	    //根据ID查找对应的收藏
	    model.addAttribute("book", gs.getBook(uid));
	    model.addAttribute("booksize", gs.getBook(uid).size());
	    
		return "grzx/grzx";
	}
	
	@RequestMapping(value = "/getQues", method = RequestMethod.POST)
	@ResponseBody
	public List<Message>  getQues(Model model,String pid){
	//	System.out.println(pid+"+=========================");
		List<Message> questionss=gs.getpMessage(Integer.valueOf(pid)); 
		model.addAttribute("questions", questionss);
		return questionss;
		//model.addAttribute("sss", "ssss");
		
	}
	
	/**
	 * Ajax请求校验email是否唯一。
	 */
	@RequestMapping(value = "/grzx/checkEmail/{id}")
	@ResponseBody
	public String checkEmail(@PathVariable("id") Long id, @RequestParam("email") String email) {
		User user = accountService.findByEmail(email);
		if (user == null) {
			return "true";
		} else {
			if(user.getId().equals(id)){
				return "true";
			}			
			return "false";
		}
	}
	
	/**
	 * Ajax请求校验email是否唯一。
	 */
	@RequestMapping(value = "/grzx/checkPwd/{id}")
	@ResponseBody
	public String checkPwd(@PathVariable("id") Long id, @RequestParam("password") String password) {
		User user = gs.getUser(id);
		boolean rtn = accountService.validatePassword(user, password);
		if (rtn) {
			return "true";
		} else {
			return "false";
		}
	}
	
	@RequestMapping(value = "/grzx/profile", method = RequestMethod.POST)
	public String update(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model, ServletRequest request) {
		User user = new User();
		if (id != -1) {
			user = gs.getUser(id);
			String name = request.getParameter("name");
			String sex = request.getParameter("sex");
			String dtBirthday = request.getParameter("dtBirthday");
			String email = request.getParameter("email");
			String adress = request.getParameter("adress");
			String phone = request.getParameter("phone");
			user.setName(name);
			user.setSex(sex);
			if(null != dtBirthday && !dtBirthday.trim().equals(""))
			   user.setDtBirthday(DateUtil.toDate(dtBirthday, "yyyy-MM-dd"));
			user.setEmail(email);
			user.setAdress(adress);
			user.setPhone(phone);
			accountService.updateUser(user);
			updateCurrentUserName(user.getName());
		}		
		return "redirect:/grzx";
	}

	@RequestMapping(value = "/grzx/passwd", method = RequestMethod.POST)
	@ResponseBody
	public String updatePasswd (long id, String pwd) {
		User user = new User();
		String message = null;
		try {
			if (id != -1) {
				user = gs.getUser(id);
				String plainPassword = pwd;
				user.setPlainPassword(plainPassword);
				accountService.updateUser(user);
			}	
			message = "修改用户" + user.getLoginName() + "密码成功";
		} catch (Exception e) {
			// TODO: handle exception
			message = "修改密码失败";
		}
		return message;
	}
	
	
	@ModelAttribute
	public void getUser(
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		if (id != -1) {
			model.addAttribute("user", gs.getUser(id));
		}
	}

	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;

	}
	/**
	 * 更新Shiro中当前用户的用户名.
	 */
	private void updateCurrentUserName(String userName) {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		user.name = userName;
	}
	
}
